<template>
	<view class="login_box">
		<view class="text_login">
			<!-- logo -->
			<image class="login_logo"  src="../../static/logo/orange.png" alt="" />
			
			<!-- 表单区域 -->
			<view class="login_phone">
				<text>手机号</text>
				<input type="text" v-model="phone" maxlength="11" />
			</view>
			<view class="login_code">
				<text>验证码</text>
				<input type="text" v-model="code" maxlength="4" />
				<view hover-class="touchOpacity" @click="getCode">{{codeBtnText}}</view>
			</view>
			
			<!-- 登录按钮 -->
			<view class="login_but" hover-class="touchOpacity" >
				<text space="ensp" @click="login">登    录</text> 
			</view>
		</view>
	</view>
</template>

<script>

	export default {
		data() {
			return {
				phone: '',
				code: '',
				storagePhoneCode: '',
				codeBtn: false,
				codeBtnText: '获取验证码'
			}
		},
		methods: {
			async login(){
				if(!this.storagePhoneCode) return;
				
				let [err, {data}] = await uni.request({
					method: 'POST',
					url: `${this.$baseApi}smslogin`,
					data: {
						phone: this.storagePhoneCode.phone
					}
				})
				console.log(data);
				if(err || data.code == 500){
					uni.showToast({
						title: '登录失败',
						icon: 'none'
					})
					return;
				}
				uni.setStorageSync('userinfo', data.list);
				
				uni.showToast({
					title: '登录成功',
					icon: 'none'
				});
				
				setTimeout(() => {
					uni.switchTab({
						url: `/pages/index/index`
					})
				}, 2000);
			},
			
			// 获取验证码
			async getCode(){
				const reg = /^1[3|4|5|6|7|8|9][0-9]{8}$/;
				if(!reg.test(this.phone) && this.phone.length != 11){
					console.log(1);
					uni.showToast({
						title: '手机号码不正确',
						icon: 'none'
					});
					return;
				}
				
				// 30秒发送一次验证码
				if(this.codeBtn) return;
				this.codeBtn = true;
				let time = 5;
				let timer = setInterval(() => {
					time--;
					this.codeBtnText = time + '后再次获取';
					
					if(time < 0){
						clearInterval(timer);
						this.codeBtn = false;
						this.codeBtnText = '获取验证码';
					}
				}, 1000)
				
				let [err, {data}] = await uni.request({
					url: `${this.$baseApi}sms`,
					data: {
						phone: this.phone
					}
				});
				console.log(data);
				if(err || data.code == 500){
					uni.showToast({
						title: '验证码获取失败',
						icon: 'none'
					})
					return;
				}
				uni.showToast({
					title: `验证码: ${data.list.code}`,
					icon: 'none'
				});
				this.code = data.list.code;
				
				this.storagePhoneCode = {phone: this.phone, code: this.code};
			}
		}
}
</script>

<style>
	/* 引入样式 */
	@import url("@/static/css/textlogin.css");
</style>
